package com.davidniu.lesson04;

import com.davidniu.lesson02.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestTransaction2 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            //关闭数据库的自动commit,会自动开启事务
            conn.setAutoCommit(false);

            String sql1 =  "update account set `money`=money-100 where `NAME` ='A'";
            stmt = conn.prepareStatement(sql1);
            stmt.executeUpdate();

            int x= 1/0; //报错

            String sql2 =  "update account set `money`=money+100 where `NAME` ='B'";
            stmt = conn.prepareStatement(sql2);
            stmt.executeUpdate();

            //业务完毕，提交事务
            conn.commit();
            System.out.println("操作成功！");

        } catch(SQLException e){
            //try{
              //  conn.rollback();// 不写也会回滚  默认回滚
            //}catch (SQLException e1){
              //  e1.printStackTrace();
            //}
            e.printStackTrace();
        } finally {
            JdbcUtils.release(conn, stmt, rs);
        }
    }
}
